<template>
    <div class="app-container">
      <div class="filter-container">
        <el-autocomplete
          v-model="listQuery.addressName"
          :fetch-suggestions="loadCities"
          placeholder="请选择城市"
          class="filter-item"
          @select="handleSelect">
        </el-autocomplete>
  
        <el-input v-model="listQuery.phone" placeholder="请输入手机号" style="width: 200px;" class="filter-item"/>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          Search
        </el-button>
      </div>
  
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="ID" prop="id" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
        <el-table-column label="城市" prop="address" align="center">
          <template slot-scope="{row}">
            <span>{{ getCityName(row.address) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="乘客手机号" prop="passengerPhone" align="center">
          <template slot-scope="{row}">
            <span>{{ row.passengerPhone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="司机手机号" prop="driverPhone" align="center">
          <template slot-scope="{row}">
            <span>{{ row.driverPhone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="车牌号" prop="vehicleNo" align="center">
          <template slot-scope="{row}">
            <span>{{ row.vehicleNo }}</span>
          </template>
        </el-table-column>
        <el-table-column label="起点" prop="departure" align="center">
          <template slot-scope="{row}">
            <span>{{ row.departure }}</span>
          </template>
        </el-table-column>
        <el-table-column label="终点" prop="destination" align="center">
          <template slot-scope="{row}">
            <span>{{ row.destination }}</span>
          </template>
        </el-table-column>
        <el-table-column label="距离（米）" prop="driveMile" align="center">
          <template slot-scope="{row}">
            <span>{{ row.driveMile }}</span>
          </template>
        </el-table-column>
        <el-table-column label="时间（分钟）" prop="driveTime" align="center">
          <template slot-scope="{row}">
            <span>{{ row.driveTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="价格（元）" prop="price" align="center">
          <template slot-scope="{row}">
            <span>{{ row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" prop="orderStatus" align="center">
          <template slot-scope="{row}">
            <span>{{ getOrderStatus(row.orderStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="primary" size="mini" @click="handleUpdate(row)">
              Edit
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
              Delete
            </el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
          <el-form-item label="订单状态" prop="orderStatus">
            <!-- 订单状态1：订单开始 2：司机接单 3：去接乘客 4：司机到达乘客起点 5：乘客上车，司机开始行程 6：到达目的地，行程结束，未支付 7：发起收款 8: 支付完成 9.订单取消 -->
            <el-radio-group v-model="temp.orderStatus">
              <el-radio :label="1">订单开始</el-radio>
              <el-radio :label="2">司机接单</el-radio>
              <el-radio :label="3">去接乘客</el-radio>
              <el-radio :label="4">到达起点</el-radio>
              <el-radio :label="5">开始行程</el-radio>
              <el-radio :label="6">到达目的地</el-radio>
              <el-radio :label="7">待支付</el-radio>
              <el-radio :label="8">已支付</el-radio>
              <el-radio :label="9">订单取消</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            Cancel
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createDate():UpdateDate()">
            Confirm
          </el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { getOrderList, updateOrder, getDicDistrict } from '@/api/order.js'
  import waves from '@/directive/waves' // waves directive
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  
  export default {
    name: 'driver',
    components: { Pagination },
    directives: { waves },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20
        },
        filteredCities: {}, // 存储筛选后的城市
        cityNameToCode: {}, // 用于存储城市名称到编码的映射
        cityCodeToName: {}, // 用于存储城市编码到名称的映射
        temp: {
          orderStatus: 1
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '新增'
        },
        downloadLoading: false
      }
    },
    created() {
      this.getDicDistrict();
      this.getList();
    },
    methods: {
        getDicDistrict() {
            getDicDistrict().then(resp => {
            const data = resp.data;
            const cityNameToCode = {};
            const cityCodeToName = {};
            for (const item of data) {
                cityNameToCode[item.addressName] = item.addressCode;
                cityCodeToName[item.addressCode] = item.addressName;
            }
            this.cityNameToCode = cityNameToCode;
            this.cityCodeToName = cityCodeToName;
            });
        },
        
        getList() {
            this.listLoading = true
            getOrderList(this.listQuery).then(response => {
            this.list = response.data.items
            this.total = response.data.total
    
            setTimeout(() => {
                this.listLoading = false
            }, 1.5 * 1000)
            })
        },
        getCityName(cityCode) {
            return this.cityCodeToName[cityCode];
        },
    
        loadCities(queryString, cb) {
            if (queryString === '') {
            cb(this.cityNameToCode.map(cityName => ({ value: cityName, code: this.cityNameToCode[cityName] })));
            } else {
            const results = Object.keys(this.cityNameToCode)
                .filter(city => city.includes(queryString))
                .map(cityName => ({ value: cityName, code: this.cityNameToCode[cityName] }));
            cb(results);
            }
        },
    
        handleSelect(item) {
            // 更新显示值为城市名称
            this.listQuery.addressName = item.value;
            // 同时更新实际的城市代码
            this.listQuery.address = item.code;
        },
    
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
    
        handleModifyStatus(row, status) {
            this.$message({
            message: '操作Success',
            type: 'success'
            })
            row.status = status
        },
        
        handleUpdate(row) {
            this.dialogStatus = 'update';
            this.dialogFormVisible = true;
            this.temp = {
                id: row.id,
                orderStatus: row.orderStatus
            };
            this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate();
            });
        },
    
        handleDelete(row, index) {
            this.$notify({
            title: 'Success',
            message: 'Delete Successfully',
            type: 'success',
            duration: 2000
            })
            this.list.splice(index, 1)
        },

        getOrderStatus(num){
            switch(num){
                case 1:
                    return "订单开始";
                case 2:
                    return "司机接单";
                case 3:
                    return "去接乘客";
                case 4:
                    return "到达起点";
                case 5:
                    return "开始行程";
                case 6:
                    return "到达目的地";
                case 7:
                    return "待支付";
                case 8:
                    return "已支付";
                case 9:
                    return "订单取消";
                default:
                    return "未知";
            }
        },

  
        UpdateDate() {
            console.log(this.temp);
            updateOrder(this.temp).then(() => {
                this.dialogFormVisible = false;
                this.getList();
            }).catch(error => {
                console.error('Failed to update item:', error);
            });
        },
    },
  
    watch: {
      'listQuery.addressName'(newVal) {
        // 当新值为空时，也将城市代码设置为空
        if (!newVal) {
          this.listQuery.address = '';
        }
      }
    }
  }
  </script>